﻿using System;
using System.Text;
using System.Threading;
using uPLibrary.Networking.M2Mqtt;
using aiot_paho_csharp;
using uPLibrary.Networking.M2Mqtt.Messages;

namespace aiot_paho_mqtt_csharp
{
    class Program
    {
        public static void TestRun()
        {
            String productKey = "k0re8OYQdFu";
            String deviceName = "danmaku_monitor";
            String deviceSecret = "3b52dbb8494c3e5f6b8eb90451dfcfa6";

            //计算Mqtt建联参数
            MqttSign sign = new MqttSign();
            sign.calculate(productKey, deviceName, deviceSecret);

            Console.WriteLine("username: " + sign.getUsername());
            Console.WriteLine("password: " + sign.getPassword());
            Console.WriteLine("clientid: " + sign.getClientid());

            //使用Paho链接阿里云物联网平台
            int port = 443;
            String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
            //broker = "47.100.6.214";

            MqttClient mqttClient = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
            mqttClient.Connect(sign.getClientid(), sign.getUsername(), sign.getPassword());

            Console.WriteLine("broker: " + broker + " Connected");

            //Paho Mqtt 消息订阅
            String topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

            mqttClient.MqttMsgPublishReceived += MqttPostProperty_MqttMsgPublishReceived;
            mqttClient.Subscribe(new string[] { topicReply }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
            Console.WriteLine("subscribe: " + topicReply);

            //Paho Mqtt 消息发布
            String topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
            String message = "haha i am monritor";
            mqttClient.Publish(topic, Encoding.UTF8.GetBytes(message));
            Console.WriteLine("publish: " + message);

            //while(true) {
            //    Thread.Sleep(2000);
            //}

            //Paho Mqtt 断开连接
            //mqttClient.Disconnect();
        }

        private static void MqttPostProperty_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("reply topic  :" + e.Topic);
            Console.WriteLine("reply payload:" + Encoding.UTF8.GetString(e.Message, 0, e.Message.Length));
        }
    }
}
